package com.wushi.lenovo.asia5b.app_utils;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;

import java.io.File;

/**
 * Created by zhangyuncai on 2019/1/16.
 * 查看文件是否存在不需要权限,但是读取,写入必须要权限
 */
public class WFileUtil {
    public static String APP_NAME = "asia5bnew";
    public static String IMAGE_FOLDER = "image-path";
    public static String PDF = "pdf";

    //创建图片路径,固定路径为 0/asia5bnew/image-path/name.png
    public static String createImagePath(Context context, String name) {
        String publicDownloadPath = getPublicDownloadPath(context);
        if (!TextUtils.isEmpty(publicDownloadPath)) {
            return publicDownloadPath + "/" + name + ".png";
        }
        String fileDir = getFileDir(context, IMAGE_FOLDER);
        return fileDir + "/" + name + ".png";
    }

    //创建pdf路径,固定路径为 0/asia5bnew/pdf/name.pdf
    public static String createPdfPath(Context context, String name) {
        String publicDownloadPath = getPublicDownloadPath(context);
        if (!TextUtils.isEmpty(publicDownloadPath)) {
            return publicDownloadPath + "/" + name + ".pdf";
        }
        String fileDir = getFileDir(context, PDF);
        return fileDir + "/" + name + ".pdf";
    }

    //创建文件夹,固定路径为 0/asia5bnew/folder
    public static String getFileDir(Context context, String folder) {
        String dir = getDir(context);
        String path = dir + "/" + APP_NAME + "/" + folder;
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        return path;
    }

    //获取外部储存根路径,固定路径为 0/
    private static String getDir(Context context) {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        } else {
            return context.getFilesDir().getAbsolutePath();
        }
    }

    /**
     * 获取缓存路径
     */
    public static String getDiskCachePath(Context context) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            return context.getExternalCacheDir().getPath();
        } else {
            return context.getCacheDir().getPath();
        }
    }

    /**
     * 获取公共下载目录
     *
     * @param context
     * @return
     */
    public static String getPublicDownloadPath(Context context) {
        return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
    }
}
